class <%= @migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
  def change
<%- unless update? || only_trigger? || detached? -%>
    add_column :<%= table_name %>, :log_data, :jsonb
<%- end -%>

<%- if fx? -%>
  <%- if previous_version -%>
    update_trigger :logidze_on_<%= table_name %>, on: :<%= table_name %>, version: <%= next_version %>, revert_to_version: <%= previous_version %>
  <%- else -%>
    reversible do |dir|
      dir.up do
    <%- if update? -%>
        # Drop legacy trigger if any (<1.0)
        execute <<~SQL
          DROP TRIGGER IF EXISTS "logidze_on_<%= full_table_name %>" on "<%= full_table_name %>";
        SQL

    <%- end -%>
        create_trigger :logidze_on_<%= table_name %>, on: :<%= table_name %>
      end

      dir.down do
        execute <<~SQL
          DROP TRIGGER IF EXISTS "logidze_on_<%= full_table_name %>" on "<%= full_table_name %>";
        SQL
      end
    end
  <%- end -%>
<%- else -%>
    reversible do |dir|
      dir.up do
  <%- if update? -%>
        execute <<~SQL
          DROP TRIGGER IF EXISTS "logidze_on_<%= full_table_name %>" on "<%= full_table_name %>";
        SQL

  <%- end -%>
        execute <<~SQL
<%= inject_sql(after_trigger? ? "logidze_after.sql" : "logidze.sql", indent: 10) %>
        SQL
      end

      dir.down do
  <%- if update? -%>
        # NOTE: We have no idea on how to revert the migration
        # ('cause we don't know the previous trigger params),
        # but you can do that on your own.
        #
        # Uncomment this line if you want to raise an error.
        # raise ActiveRecord::IrreversibleMigration
  <%- else -%>
        execute <<~SQL
          DROP TRIGGER IF EXISTS "logidze_on_<%= full_table_name %>" on "<%= full_table_name %>";
        SQL
  <%- end -%>
      end
    end
<%- end -%>
<%- if backfill? -%>
    reversible do |dir|
      dir.up do
        <%- if detached?  %>
          execute <<~SQL
            INSERT INTO <%= quoted_log_data_table_name %> (log_data, loggable_type, loggable_id)
            SELECT logidze_snapshot(<%= logidze_snapshot_parameters %>), <%= detached_loggable_type %>, t.id
            FROM "<%= full_table_name %>" t
            ON CONFLICT (loggable_type, loggable_id)
            DO UPDATE
            SET log_data = EXCLUDED.log_data;
          SQL
        <%- else %>
          execute <<~SQL
            UPDATE "<%= full_table_name %>" as t
            SET log_data = logidze_snapshot(<%= logidze_snapshot_parameters %>);
          SQL
        <%- end %>
      end
    end
<%- end -%>
  end
end
